package com.shi.shiro.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import com.shi.shiro.domain.Permission;
import com.shi.shiro.domain.Role;
import com.shi.shiro.domain.User;
import com.shi.shiro.domain.UserRole;
import com.shi.shiro.mapper.UserMapper;
import com.shi.shiro.service.RoleService;
import com.shi.shiro.service.UserRoleService;
import com.shi.shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import static com.shi.shiro.common.Constants.*;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleService roleService;

    @Resource
    private UserRoleService userRoleService;
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return userMapper.selectRolesByUserId(userId);
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return userMapper.selectPermissionsByRoleId(roleId);
    }

    @Transactional
    @Override
    public boolean registerUser(User user) {
        // 判断是否存在该用户名
        User selected = userMapper.selectUserByUsername(user.getUsername());
        Assert.isTrue(ObjUtil.isEmpty(selected),"该用户名已存在");
        LocalDateTime now = LocalDateTime.now();
        // 对密码进行加盐加密
        String salt = RandomUtil.randomString(DEFAULT_SALT_LENGTH);
        String hashPassword = new Md5Hash(user.getPassword(), salt).toHex();
        user.setSalt(salt);
        user.setPassword(hashPassword);
        // 填充默认头像
        user.setAvatar(DEFAULT_AVATAR);
        user.setCreateTime(now);
        user.setUpdateTime(now);
        // 用户表添加
        boolean b=userMapper.insertUser(user);
        // 角色表添加
        Role role = Role.builder().roleName(DEFAULT_ROLE).createTime(now).updateTime(now).build();
        boolean b1=roleService.saveRole(role);
        // 用户角色表添加
        UserRole userRole = UserRole.builder().userId(user.getId()).roleId(role.getId()).createTime(now).updateTime(now).build();
        boolean b2 = userRoleService.saveUserRole(userRole);
        return b&&b1&&b2;
    }
}
